package org.example.algorithm.doublepointer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ThreeSumSolution {

    public static void main(String[] args) {
        int[] nums = {-1,0,1,2,-1,-4};
        ThreeSumSolution solution = new ThreeSumSolution();
        List<List<Integer>> res = solution.threeSum(nums);
        System.out.println(res);
    }

    //快速跳过重复值
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums.length == 0) {
            return res;
        }
        Arrays.sort(nums);
        for (int i=0;i<nums.length-2;i++) {
            if (nums[i] + nums[i+1] + nums[i+2] > 0) {
                break;
            }
            if (nums[i] + nums[nums.length-1] + nums[nums.length-2] < 0) {
                continue;
            }
            if (i >= 1 && nums[i] == nums[i-1]) {
                continue;
            }
            int left = i+1;
            int right = nums.length-1;
            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == 0) {
                    res.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    for (left++;left<right && nums[left] == nums[left-1];left++);
                    for (right--;right>left && nums[right] == nums[right+1];right--);
                } else if(sum < 0) {
                    left++;
                } else {
                    right--;
                }
            }
        }
        return res;
    }

    public List<List<Integer>> threeSum2(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if (nums.length == 0) {
            return res;
        }
        Arrays.sort(nums);
        for (int i=0;i<nums.length-2;i++) {
            if (nums[i] + nums[i+1] + nums[i+2] > 0) {
                break;
            }
            if (nums[i] + nums[nums.length-1] + nums[nums.length-2] < 0) {
                continue;
            }
            if (i >= 1 && nums[i] == nums[i-1]) {
                continue;
            }
            int left = i+1;
            int right = nums.length-1;
            while (left < right) {
                if (left > i+1 && nums[left] == nums[left-1]) {
                    left++;
                    continue;
                }
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == 0) {
                    res.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    left++;
                } else if(sum < 0) {
                    left++;
                } else {
                    right--;
                }
            }
        }
        return res;
    }
}
